package logic

import (
	"context"
	"course_srv/course"
	"course_srv/internal/svc"
	"course_srv/models/es"
	"course_srv/models/mysql"
	"course_srv/models/redis"
	"errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type CourseAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCourseAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CourseAddLogic {
	return &CourseAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CourseAddLogic) CourseAdd(in *course.CourseAddRequest) (*course.CourseAddResponse, error) {
	// todo: add your logic here and delete this line

	c := mysql.Course{
		Name:  in.Name,
		Stock: int(in.Stock),
		Price: float64(in.Price),
		Cover: in.Cover,
		Intro: in.Intro,
	}
	err := c.Add()
	if err != nil {
		return nil, errors.New("课程发布失败")
	}
	//同步到es
	err = es.SyncCourseEs(c)
	if err != nil {
		return nil, errors.New("es同步失败")
	}
	//同步到redis哈希
	redis.SyncCourseStock(int(c.ID), c.Stock)

	return &course.CourseAddResponse{Id: int32(c.ID)}, nil
}
